<?php
/**
 * CommonLogic.class.php - 公共逻辑
 * @package Logic
 * @subpackage null
 * @link http://www.xxx.com
 * @author xxx PHP DEV TEAM JiRY(390066398@qq.com)
 * @copyright 2016-10-31 14:40
 */
namespace Common\Logic;

class CommonLogic {
    protected $modelName = null;
    /**
     * 管理员登陆信息
     * @var array
     */
    protected static $loginInfo = array();
    
    /**
     * 默认返回
     * @var array
     */
    public $result = array('status' => 0);
    
    public function __construct(){
        $storage_type       = C('LOGIN_STORAGE_TYPE');
        $session_key        = C('AUTH_CONFIG.AUTH_SESSION_KEY');
        
        switch( $storage_type ){
            case 'session':
                self::$loginInfo = session($session_key);
                break;
            case 'redis':
                break;
            case 'memcache':
                break;
        }
    }
    
    /**
     * 获取管理员登陆信息
     */
    public function getLoginInfo(){
        return self::$loginInfo;
    }
    
    /**
     * 存储登陆数据
     * @param array $data       管理员数据
     */
    public function storageLoginData($data){
        $auth_key           = C('AUTH_CONFIG.AUTH_KEY');
        $storage_type       = C('LOGIN_STORAGE_TYPE');
        $session_key        = C('AUTH_CONFIG.AUTH_SESSION_KEY');
        
        switch( $storage_type ){
            case 'session':
                //登陆成功session写入登陆token
                session($auth_key , $data['id']);
                session($session_key , $data);
                break;
            case 'redis':
                break;
            case 'memcache':
                break;
            default:
            	//登陆成功session写入登陆token
                session($auth_key , $data['id']);
                session($session_key , $data);
                break;
        }
    }
    
    /**
     * 删除登陆数据
     */
    public function deleteLoginData(){
        $auth_key           = C('AUTH_CONFIG.AUTH_KEY');
        $storage_type       = C('LOGIN_STORAGE_TYPE');
        $session_key        = C('AUTH_CONFIG.AUTH_SESSION_KEY');
    
        switch( $storage_type ){
            case 'session':
                session($auth_key , null);
                session($session_key , null);
                break;
            case 'redis':
                break;
            case 'memcache':
                break;
            default:
            	session($auth_key , null);
                session($session_key , null);
                break;
        }
    }
    
    /**
     * 获取模型对象
     * @param string $modelName         模型名称
     * @return boolean|object
     */
    protected function getModel($modelName){
        if($modelName && !empty($modelName)) {
            $_model = $modelName;
        }else{
            if(!empty($this -> modelName)) {
                $_model = $this->modelName;
            }else{
                return false;
            }
        }
        return D($_model) ? D($_model) : M($_model);
    }
    
    /**
     * 获取字段
     * @param string $modelName     表模型名
     * @param string $field         字段名称
     * @param array $condition      查询条件
     * @return string
     */
    public function getField($modelName, $field, $condition=array()){
        $model = self::getModel($modelName);
        $model = $model->where($condition);
        return $model->getField($field);
    }
    
    /**
     * 获取单条数据
     * @param string $modelName     表模型名
     * @param array $condition      查询条件
     * @param array $field          获取字段
     * @return array|boolean|null
     */
    public function getRow($modelName, $condition=array(), $field=array()){
        $model = self::getModel($modelName);
        
        if( is_array($field) && !empty($field) )
            $model = $model->field($field);
        
        if( is_array($condition) && !empty($condition) )
            $model = $model->where($condition);
        
        return $model->find();
    }
    
    /**
     * 获取多条数据
     * @param string $modelName            表模型名称
     * @param string|array $condition      查询条件
     * @param string|array $field          获取字段
     * @param string|array $sort           排序规则
     * @param int $limit                   获取行数
     * @param string|array $group          分组
     * @return array
     */
    public function getRows($modelName, $condition='', $field='', $sort='', $limit=0, $group=''){
        $model = self::getModel($modelName);
        
        if( $field )
            $model = $model->field($field);
        
        if( $condition )
            $model = $model->where($condition);
        
        if( $sort )
            $model = $model->order($sort);
        
        if( $limit )
            $model = $model->limit($limit);
        
        if( $group )
            $model = $model->group($group);

        return $model->select();
    }


    public function getRowsCount($condition = null, $modelName = null){
        $model = self::getModel($modelName);

        if( $condition )
            $model = $model->where($condition);

        $rs = $model -> count();

        return $rs?$rs:0;
    }
    /**
     * 数据分页
     * @author JiRY
     * @param array $modelParams    模型参数（name：模型名、field：字段列表、where：查询条件、order：排序）
     * @param array $map            POST提交或其他查询条件
     * @param int $pageIndex        当前页数
     * @param int $pageSize         每页条数
     * @return array                分页导航数据
     */
    public function page($modelParams, $map = array(), $pageIndex = 1, $pageSize = 0){
        if( !array_key_exists('name', $modelParams) || empty($modelParams['name']) )
            return false;
        
        $model  = $this->getModel($modelParams['name']);     
        
        if( array_key_exists('join', $modelParams) && !empty($modelParams['join']) )
            $model = $model->join($modelParams['join']);
        
        if( array_key_exists('alias', $modelParams) && !empty($modelParams['alias']) )
            $model = $model->alias($modelParams['alias']);
        
        if( array_key_exists('union', $modelParams) && !empty($modelParams['union']) )
            $model = $model->alias($modelParams['union']);
        
        $pageIndex  = $_GET['p'] ? $_GET['p'] : $pageIndex ;
        
        $any_value = $modelParams['any_value']?$modelParams['any_value']:'id';
        
        //$count      = $model->field("any_value(id) as id")->where($modelParams['where']);
        //$count      = $model->field("any_value({$any_value}) as {$modelParams['name']}_id")->where($modelParams['where']);
        $count      = $model->field("any_value($any_value)")->where($modelParams['where']);
        
        if( array_key_exists('group', $modelParams) && !empty($modelParams['group']) ){
            $sub_query  = $count->group($modelParams['group'])->buildSql();
            $count = M()->table($sub_query.' a')->count();
        }else{
            $count = $count->count();
        }
        
        if( $pageSize <= 0 ) $pageSize = C('PAGE_SIZE');
            
        //总页数
        $all_page   = ceil($count / $pageSize);
    
        // 实例化分页类 传入总记录数和每页显示的记录数
        $Page       = new \Think\Page( $count , $pageSize );
        
        //分页跳转的时候保证查询条件
        if( !empty($map) && is_array($map) ){
            foreach($map as $key=>$val) {
                $Page->parameter[$key]   =   urlencode($val);
            }
        }
    
        $model  = $this->getModel($modelParams['name']);   
        
        if( array_key_exists('field', $modelParams) && !empty($modelParams['field']) )
            $model = $model->field($modelParams['field']);
    
        if( array_key_exists('order', $modelParams) && !empty($modelParams['order']) )
            $model = $model->order($modelParams['order']);
        
        if( array_key_exists('group', $modelParams) && !empty($modelParams['group']) )
            $model = $model->group($modelParams['group']);
        
        if( array_key_exists('join', $modelParams) && !empty($modelParams['join']) )
            $model = $model->join($modelParams['join']);
        
        if( array_key_exists('alias', $modelParams) && !empty($modelParams['alias']) )
            $model = $model->alias($modelParams['alias']);
        
        if( array_key_exists('union', $modelParams) && !empty($modelParams['union']) )
            $model = $model->alias($modelParams['union']);

    
        //记录
        $list = $model->where($modelParams['where'])->page($pageIndex.','.$pageSize)->select();

        // 分页显示输出
        $show       = $Page->show();

        return array(
            'all_page'      => $all_page,
            'totalCount'    => $count,
            'page'          => $pageSize,
            'list'          => $list,
            'numPerPage'    => $pageIndex,
            'pagehtml'      => urldecode($show)
        );

    }
    
    /**
     * API 接口分页
     * @param array $params         分页参数
     */
    public function apiPage($params=[]){
        // 当前页码
        $_GET['p']      = I('post.page', 1);
        // 每页显示条数
        $limit          = I('post.limit', 20);
        // 分页最大行数
        $max_limit = C('PAGE_MAX_LIMIT') ? C('PAGE_MAX_LIMIT') : 100;

        // 限制分页最大值
        if($limit > $max_limit){
            $limit = $max_limit;
        }
        
        // 分页参数
        $table_name = (array_key_exists('table', $params) && $params['table']) ? $params['table'] : null;
        $where      = (array_key_exists('where', $params) && $params['where']) ? $params['where'] : '';
        $order      = (array_key_exists('order', $params) && $params['order']) ? $params['order'] : '';
        
        if(!$table_name){
            return false;
        }
        
        $model = M($table_name);
        // 记录总数
        $count = $model->where($where)->count();
        $page  = new \Think\Page($count, $limit);
        // 记录列表
        $list  = $model->where($where)->order($order)->limit($page->firstRow.','.$page->listRows)->select();
        
        $result['code']     = 0;
        $result['count']    = $count;
        $result['data']     = $list;
        return $result;
    }
    
    /**
     * 记录是否存在
     * @param string $modelName         模型名称
     * @param array $condition          查询条件
     * @return boolean    
     */
    public function rowExists($modelName, $condition=array()){
        $model = self::getModel($modelName);
        
        $result = $model->where($condition)->find();
        
        if( $result ){
            return false;
        }
        
        return true;
    }
    
    /**
     * 获取多行单个字段
     * @param string $modelName               模型名称
     * @param string|array $field             获取字段             
     * @param array $condition                查询条件
     * @return array
     */
    public function getFields($modelName, $field, $condition=array()){
        $model = self::getModel($modelName);
        
        return $model->field($field)->where($condition)->select();
    }
    
    /**
     * 删除单行或多行记录
     * @param string $modelName         模型名称
     * @param array $condition          删除条件
     * @return boolean
     */
    public function deleteRows($modelName, $condition=array()){
        if(!$modelName || empty($condition)){
            return false;
        }
        
        $model = self::getModel($modelName);
        
        $result = $model->where($condition)->save(array('data_status'=>99));
        
        if( $result === false ){
            return false;
        }
        
        return true;
    }
    
    /**
     * 启停用单行或多行记录
     * @param string $modelName         模型名称
     * @param array $condition          条件
     * @param string $flag              操作标识；on：启用、off：停用、other：其他
     * @param string $field             其他操作，影响字段
     * @param string $value             其他操作，影响字段值
     * @return boolean
     */
    public function onOffRows($modelName, $condition=array(), $flag, $field='', $value=''){
        if(!$modelName || empty($condition)){
            return false;
        }
    
        $model = self::getModel($modelName);
        
        $status = $flag == 'on' ? 1 : 2;
        //if($flag == 'other') $status = 3;
        if($flag == 'other'){
            $result = $model->where($condition)->save([$field=>$value]);
        }else{
            $result = $model->where($condition)->save(array('data_status'=>$status));
        }


    
        if( $result === false ){
            return false;
        }
    
        return true;
    }
    
    /**
     * 通过MD5值获取，资源ID
     * @param string $md5_value         MD5值
     * @return number|string            
     */
    public function getResourceId($md5_value){
        $resource_map = array(
            'res_md5val'        => $md5_value,
            'data_status'       => 1
        );
        $resource_id        = $this->getField('Resource', 'id', $resource_map);
        
        return $resource_id ? $resource_id : 0;
    }
    
    /**
     * 记录登陆日志
     * @param array $info               日志参数信息
     * @param int $info['admin_id']     管理员ID
     * @param string $info['log_msg']   日志信息
     * @return boolean
     */
    public function recodeLog($info){
        $module = self::getModel('AdminLogs');
        
        $data = array(
            'admin_id'              => $info['admin_id'] ? $info['admin_id'] : self::$loginInfo['id'],
            'control_name'          => CONTROLLER_NAME,
            'action_name'           => ACTION_NAME,
            'ip_address'            => $_SERVER['REMOTE_ADDR'],
            'log_type'              => $info['log_type'] ? $info['log_type'] : 1,
            'log_msg'               => $info['log_msg'],
            'create_time'           => time()
        );
        
        if($module->add($data)){
            return true;
        }
        
        return false;
    }


    /**
     * 更新数据信息
     * @param array $field_data         更新字段
     * @param array $condition          更新条件
     * @param null $modelName           模型名称
     * @return bool
     */
    public function updateData($field_data = [], $condition = [], $modelName = null){
        $_model = self::getModel($modelName);
        if($_model){
            if($field_data && !empty($field_data) && is_array($field_data)){
                $rs = $_model -> where($condition) -> save($field_data);

                if($rs){
                    return true;
                }
            }
        }

        return false;
    }


    /**
     * 新增数据信息
     * @param array $field_data       待插入数据
     * @param bool  $is_batch         是否批量插入数据
     * @param bool  $return_sql       是否返回SQL语句
     * @param null $modelName         模块名称
     * @return bool|mixed             成功返回插入后的最后ID值，失败返货false
     */
    public function addData($field_data = [], $is_batch = false, $return_sql = false, $modelName = null){
        $_model = self::getModel($modelName);
        if($_model){
            if($field_data && !empty($field_data) && is_array($field_data)){
                if($is_batch){
                    $rs = $_model -> fetchSql($return_sql) -> addAll($field_data);
                }else{
                    $rs = $_model -> fetchSql($return_sql) -> add($field_data);
                }

                if($rs){
                    return $rs;
                }
            }
        }

        return false;
    }
}